package com.wuhao.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuhao.springboot.entity.Part;
import com.wuhao.springboot.mapper.PartMapper;
import com.wuhao.springboot.service.PartService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;


import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description
 * @Date 2023/1/30 23:25
 * @Author pq
 */
@Service
public class PartServiceImpl extends ServiceImpl<PartMapper, Part> implements PartService  {

    @Resource
    private PartMapper partMapper;

    String uploadPath = "src/main/resources/static/img/part/";
    @Override
    public String uploadImg(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        File dest = new File(uploadPath+fileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),dest);
            String url = "http://" + "127.0.0.1" + ":" + "9090" + "/" + fileName;
            String path = uploadPath + fileName;
            System.out.println("图片上传成功，图片地址为：" + path + "url:" + url);
            return url;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addPart(Part part) {
        Part dto = partMapper.findByName(part.getName());
        if(Objects.nonNull(dto)){
            dto.setUrl(part.getUrl());
            dto.setPrice(part.getPrice());
            dto.setNum(dto.getNum()+part.getNum());
            this.updateById(dto);
        }else {
            this.save(part);
        }
    }

    @Override
    public IPage<Part> getPartByPage(int current, int size) {
        LambdaQueryWrapper<Part> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        Page<Part> partPage = new Page<>(current , size);
        IPage<Part> partIPage = partMapper.selectPage(partPage , userLambdaQueryWrapper);
        System.out.println("总页数： "+partIPage.getPages());
        System.out.println("总记录数： "+partIPage.getTotal());
        partPage.getRecords().forEach(System.out::println);
        return partIPage;
    }

    @Override
    public void delete(Integer id) {
        QueryWrapper<Part> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        this.remove(queryWrapper);
    }

    @Override
    public void update(Part part) {
        QueryWrapper<Part> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",part.getId());
        this.update(part,queryWrapper);
    }
}
